package com.qkst.website.common.core;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import com.qkst.website.common.utils.SetEnums;

/**
 * @author lh
 * @description controller权限拦截控制器
 * @date 2017-05-08
 * @email ahlxlihao@163.com
 */
public class ControllerInterceptor extends OncePerRequestFilter {

	private static final Logger log = LoggerFactory.getLogger(ControllerInterceptor.class);
	
	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String requestUrl = request.getPathInfo();
		log.info("requestUrl>>>"+requestUrl);
		if (requestUrl.equals("/")) {
			response.sendRedirect("web/index.html");
		}else if(requestUrl.indexOf("helpBargain/")>=0){//如果是砍价
			String resUrl=("/website/web/bargain/helpToBargain.html?token="+requestUrl.substring(requestUrl.lastIndexOf("/")+1));
			log.info("resUrl>>>>>"+resUrl);
			response.sendRedirect(resUrl);
		} else if( isStatic(request) || !requestUrl.equals("/web/course.html")){
			filterChain.doFilter(request, response);
		}else {
			Object object = request.getSession().getAttribute(SetEnums._LOGIN_USER.toString());
			if (null == object || null == object.toString()|| "".equals(object.toString())) {
				if (request.getHeader("x-requested-with") != null&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
					response.setHeader("sessionstatus", "timeout");//在响应头设置session状态
					//response.getWriter().print(JSON.toJSONString("timeout"));
				} else {
					response.sendRedirect("/website/");
					
				}
			}
		}
		
		/*if (isStatic(request) || isApi(request) || isWs(request)) {
			filterChain.doFilter(request, response);
		} else {
			request.getRequestDispatcher("/index.jsp").forward(request,
					response);
		}*/
	}

	/*private boolean isApi(HttpServletRequest request) {
		return request.getRequestURI().indexOf(".do") >= 0;
	}

	private boolean isWs(HttpServletRequest request) {
		return request.getRequestURI().indexOf("EtlJobLogService") >= 0
				|| request.getRequestURI().indexOf("EtlJobReportService") >= 0
				;
	}*/

	private boolean isStatic(HttpServletRequest request) {
		return Pattern.matches(
				".+\\.((css)|(js)|(woff)|(ttf)|(map)|(woff2)|(eot)|(svg)|(otf)|(png)|(jpg)|(gif)|(ico)|(txt))$",
				request.getRequestURI());
	}
}
